﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using DbControl;
using Common;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using System.Configuration;
using static System.Collections.Specialized.BitVector32;

namespace Communicate
{
    internal class lMqttC
    {
        private MqttClient mqttClient = null;
        public bool IsClose { get; set; } = false;
        private void ConnectMqttServer()
        {
            MqttFactory mqttFactory = new MqttFactory();
            if (mqttClient == null)
            {
                mqttClient = (MqttClient)mqttFactory.CreateMqttClient();
                mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
                mqttClient.ConnectedAsync += MqttClient_ConnectedAsync;
                mqttClient.DisconnectedAsync += MqttClient_DisconnectedAsync;
            }
            ConnectToServer();
        }
        private async void InitMqttServer()
        {
            try
            {
                Task.Run(async () => { ConnectMqttServer(); });
            }
            catch (Exception ex)
            {
                //MessageBox.Show("服务启动失败，清重启", "提示");
                lLogWrite.WriteLog("启动服务失败!" + ex.ToString());
            }

        }
        private async void ConnectToServer()
        {
            try
            {
                var mqttClientOptions = new MqttClientOptionsBuilder()
                    .WithTcpServer(mqtthelper.mServerIp, mqtthelper.mServerPort) //("101.200.47.148", 1883)
                    .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
                    .WithClientId(mqtthelper.mClientUUID)// + Guid.NewGuid().ToString()"MonitoringApp"
                    .WithCleanSession(false)
                    .WithKeepAlivePeriod(TimeSpan.FromSeconds(30))
                    .WithCredentials("test", "test")
                    .Build();

                var res = await mqttClient.ConnectAsync(mqttClientOptions);
            }
            catch (Exception ex)
            {
                lLogWrite.WriteLog("连接失败原因:" + ex.Message);
              
            }
        }
        private Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            if (!IsClose)
            {
               
                   
                    lLogWrite.WriteLog("###断开重连###");
                    ConnectToServer();
              
            }
            return Task.CompletedTask;

        }
        private Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
        {
           
            //foreach (Devicelist vo in session.m_dvList)
            //{
            //    if (!string.IsNullOrEmpty(vo.dvTopic))
            //    {
            //        string topic = vo.dvTopic;
            //        mqttClient.SubscribeAsync(topic);
            //    }
            //}
            //string topic = "testdv1101/msg";
            //mqttClient.SubscribeAsync(topic);
            return Task.CompletedTask;
        }
        private Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {

            return Task.CompletedTask;
        }
    }
}
